package Service;

import DAO.BookDAO;
import DATA.Book;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;





///////////////////为了给map排序我还要手动自定义一个类
class Entry implements Comparable<Entry> {
    private String key;
    private Integer value;

    public Entry(String key, Integer value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public Integer getValue() {
        return value;
    }

    @Override
    public int compareTo(Entry o) {
        return o.getValue().compareTo(value);
    }
}


@WebServlet(name = "BookList", value = "/BookList")
public class BookList extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            List<Book> books = BookDAO.FindAll();
            Iterator<Book> iterator = books.listIterator();
            Map<String,Integer> map = new TreeMap();
            while (iterator.hasNext()) {
                Book aBook = iterator.next();
                map.put(aBook.getBookName(), aBook.getRecommend());
            }
 ///////////////////////////////////////////////////////////////////////////////////
            //上网学习的如何对一个HashMap进行排序
            // 将Map.Entry元素转换为自定义类Entry的对象并放入List集合中
            List<Entry> list = new ArrayList<>();
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                Entry e = new Entry(entry.getKey(), entry.getValue());
                list.add(e);
            }

            // 对List集合进行排序
            Collections.sort(list);

            // 将排序后的元素放入一个新的LinkedHashMap中
            Map<String, Integer> sortedMap = new LinkedHashMap<>();
            for (Entry entry : list) {
                sortedMap.put(entry.getKey(), entry.getValue());
            }

            // 输出排序后的结果
//            System.out.println(sortedMap);
 ///////////////////////////////////////////////////////////////////////////////
            request.setAttribute("books", sortedMap);
            request.getRequestDispatcher("BookList.jsp").forward(request, response);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}



